
package me.zhengjie.modules.workOrder.service.impl;

import com.alibaba.fastjson.JSONArray;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.dto.DictDetailDto;
import me.zhengjie.modules.workOrder.domain.Project;
import me.zhengjie.modules.workOrder.domain.WorkOrderDetail;
import me.zhengjie.modules.workOrder.domain.WorkOrderHead;
import me.zhengjie.modules.workOrder.repository.ProjectRepository;
import me.zhengjie.modules.workOrder.repository.WorkOrderHeadRepository;
import me.zhengjie.modules.workOrder.service.ProjectService;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.workOrder.repository.WorkOrderDetailRepository;
import me.zhengjie.modules.workOrder.service.WorkOrderDetailService;
import me.zhengjie.modules.workOrder.service.dto.WorkOrderDetailDto;
import me.zhengjie.modules.workOrder.service.dto.WorkOrderDetailQueryCriteria;
import me.zhengjie.modules.workOrder.service.mapstruct.WorkOrderDetailMapper;
import me.zhengjie.utils.excelUtil.ExcelUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author 李奎
* @date 2023-06-29
**/
@Service
@RequiredArgsConstructor
public class WorkOrderDetailServiceImpl implements WorkOrderDetailService {

    private final WorkOrderDetailRepository workOrderDetailRepository;
    private final WorkOrderDetailMapper workOrderDetailMapper;
    private final DictDetailService dictDetailService;
    private final ProjectRepository projectRepository;
    private final ProjectService projectService;
    private final WorkOrderHeadRepository workOrderHeadRepository;

    @Override
    public Map<String,Object> queryAll(WorkOrderDetailQueryCriteria criteria, Pageable pageable){
        Page<WorkOrderDetail> page = workOrderDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(workOrderDetailMapper::toDto));
    }

    @Override
    public List<WorkOrderDetailDto> queryAll(WorkOrderDetailQueryCriteria criteria){
        return workOrderDetailMapper.toDto(workOrderDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public WorkOrderDetailDto findById(String workDetailId) {
        WorkOrderDetail workOrderDetail = workOrderDetailRepository.findById(workDetailId).orElseGet(WorkOrderDetail::new);
        ValidationUtil.isNull(workOrderDetail.getWorkDetailId(),"WorkOrderDetail","workDetailId",workDetailId);
        return workOrderDetailMapper.toDto(workOrderDetail);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WorkOrderDetailDto create(WorkOrderDetail resources) {
        resources.setCreateBy(SecurityUtils.getCurrentUsername());
        return workOrderDetailMapper.toDto(workOrderDetailRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(WorkOrderDetail resources) {
        WorkOrderDetail workOrderDetail = workOrderDetailRepository.findById(resources.getWorkDetailId()).orElseGet(WorkOrderDetail::new);
        ValidationUtil.isNull( workOrderDetail.getWorkDetailId(),"WorkOrderDetail","id",resources.getWorkDetailId());
        workOrderDetail.copy(resources);
        workOrderDetail.setUpdateBy(SecurityUtils.getCurrentUsername());
        workOrderDetailRepository.save(workOrderDetail);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String workDetailId : ids) {
            WorkOrderDetail workOrderDetail = workOrderDetailRepository.findById(workDetailId).orElseGet(WorkOrderDetail::new);
            workOrderDetail.setIsDelete("0");
            workOrderDetailRepository.save(workOrderDetail);
        }
    }

    @Override
    public void download(List<WorkOrderDetailDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        String projectName = "";
        if (all.size() > 0) projectName = this.getProjectNameByWorkId(all.get(0).getWorkHeadId());
        for (WorkOrderDetailDto workOrderDetail : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("工单编号", workOrderDetail.getCreateTime());
            map.put("所属系统", projectName);
            map.put("提问人", workOrderDetail.getStartUser());
            map.put("提问时间", workOrderDetail.getStartTime());
            DictDetailDto work_type = dictDetailService.getDictByNameAndValue("work_type", workOrderDetail.getQuestionType());
            map.put("类型", work_type != null ? work_type.getLabel() : null);
            map.put("工单描述", workOrderDetail.getQuestionDescription());
            map.put("解决办法", workOrderDetail.getQuestionSolution());
            map.put("处理人", workOrderDetail.getEndUser());
            map.put("处理时间", workOrderDetail.getEndTime());
            map.put("工时(人/天)", workOrderDetail.getWorkHours());
            map.put("备注", workOrderDetail.getRemark());
            map.put("排序", workOrderDetail.getOrderNumber());
            map.put("机构编码", workOrderDetail.getEnterpriseCode());
            DictDetailDto enterprise_list = dictDetailService.getDictByNameAndValue("enterprise_list", workOrderDetail.getEnterpriseCode());
            map.put("机构名称", enterprise_list != null ? enterprise_list.getLabel() : null);
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 导入工单明细
     * @param file
     * @param headId
     */
    @Override
    public void importDetail(MultipartFile file, String headId) throws Exception {
        List<WorkOrderDetailDto> detailList = ExcelUtils.readMultipartFile(file,WorkOrderDetailDto.class);
        System.out.println("detailList = " + detailList);
        for (WorkOrderDetailDto detail : detailList) {
            detail.setWorkHeadId(headId);
            detail.setIsDelete("1");
            detail.setCreateBy("admin");
            //Excel时间处理
            String endTimeStr=detail.getEndTimeStr();
            Date setupTime = HSSFDateUtil.getJavaDate(Double.valueOf(endTimeStr));
            detail.setEndTime(new Timestamp(new Date(String.valueOf(setupTime)).getTime()));
            WorkOrderDetail newDetail=new WorkOrderDetail();
            BeanUtils.copyProperties(detail,newDetail);
            workOrderDetailRepository.save(newDetail);
        }
    }

    /**
     * 根据订单头id查询项目名称
     * @param workHeadId
     * @return
     */
    public String getProjectNameByWorkId(String workHeadId) {
        String projectName = "";
        WorkOrderHead headHead = workOrderHeadRepository.findById(workHeadId).orElseGet(WorkOrderHead::new);
        if (headHead !=null) {
            Project project = projectRepository.findById(headHead.getProjectId()).orElseGet(Project::new);
            if (project!=null) {
                projectName=project.getProjectName();
            }
        }
        return projectName;
    }
}